package com.complaint.controller;

import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.*;

import com.complaint.pojo.Complaint;
import com.complaint.pojo.Manager;
import com.complaint.pojo.User;
import com.complaint.service.ComplaintService;
import com.complaint.service.ManagerService;
import com.complaint.service.UserService;
import com.complaint.service.impl.ComplaintServiceImpl;
import com.complaint.service.impl.ManagerServiceImpl;
import com.complaint.service.impl.UserServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/user/*")
public class UserController extends BaseController {

    private int userId = 0;
    private boolean userType = false;
    private UserService userService = new UserServiceImpl();
    private ManagerService managerService = new ManagerServiceImpl();
    private ComplaintService complaintService = new ComplaintServiceImpl();

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String admin = req.getParameter("admin");
        String username = req.getParameter("username");
        String pw = req.getParameter("password");

        // 判断是管理员还是普通用户
        if (admin != null && admin.equals("manager")) {
            // 获取数据库中的密码与输入密码对比
            List<Manager> loginManager = managerService.findByName(username);
//            System.out.println(loginManager.size());
            System.out.println(loginManager.get(0).getPassword().equals(pw));
            if (loginManager.size() == 1 && loginManager.get(0).getPassword().equals(pw)) {
                // 一切成功后，一、跳转页面；二、标识管理员身份；三、标识登录用户ID
                resp.sendRedirect("/main_manager.html");

                userType = true;
                userId = managerService.findId(username);
            }
        } else if (admin == null) {
            List<User> loginUser = userService.findByName(username);
            if (loginUser.size() == 1 && loginUser.get(0).getPassword().equals(pw)) {

                resp.sendRedirect("/main_user.html");

                userId = userService.findId(username);
            }
        }
//        resp.sendRedirect("/login.html");
    }

    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 接收数据
        String admin = req.getParameter("admin");
        String username = req.getParameter("username");
        String pw1 = req.getParameter("password");
        String pw2 = req.getParameter("confirm_password");

        // 调用服务层方法，实现功能
        int rows = 0;
        if (pw1.equals(pw2)) {
            if (admin != null && admin.equals("manager")) {
                Manager manager = new Manager(username, pw1);
                rows = managerService.regist(manager);
            } else if (admin == null) {
                User user = new User(username, pw1);
                rows = userService.regist(user);
            }
        }

        // 判断执行是否成功，成功跳转
        if (rows > 0) {
            resp.sendRedirect("/login.html");
        } else {
            resp.sendRedirect("/register.html");
        }

    }

    // 跳转用户主界面后加载数据
    protected void mainUser(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // 1. 设置响应内容类型为JSON
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 2. 模拟数据（实际应从数据库查询）
        if (userId != 0 && !userType) {
            List<Complaint> data = userService.findForMain(userId);
            // 3. 将数据转为JSON字符串（需要引入Jackson/Gson库）
            ObjectMapper mapper = new ObjectMapper(); // Jackson库的类
            String jsonData = mapper.writeValueAsString(data);

            // 4. 返回数据给前端
            PrintWriter out = resp.getWriter();
            out.print(jsonData);
            out.flush();
        }

    }

    // 跳转管理员主界面后加载数据
    protected void mainManager(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // 1. 设置响应内容类型为JSON
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 2. 模拟数据（实际应从数据库查询）
        if (userId != 0 && userType) {
            List<Complaint> data = managerService.findForMain();

            // 3. 将数据转为JSON字符串（需要引入Jackson/Gson库）
            ObjectMapper mapper = new ObjectMapper(); // Jackson库的类
            String jsonData = mapper.writeValueAsString(data);

            // 4. 返回数据给前端
            PrintWriter out = resp.getWriter();
            out.print(jsonData);
            out.flush();
        }
    }

    // 接收用户界面发来的投诉信息
    protected void sendComplaint(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String title = req.getParameter("complaintTitle");
//        String userIDBef = req.getParameter("complaintUserID");
//        int userID = Integer.parseInt(userIDBef);
        int userID = 1;
        String complaining = req.getParameter("complaintComplaining");
        String complained = req.getParameter("complaintComplained");
        String content = req.getParameter("complaintContent");
        String hiddenBef = req.getParameter("complaintHidden");
        boolean hidden = hiddenBef != null && hiddenBef.equals("hidden");
        complaining = hidden ? "匿名" : complaining;
        String status = "0";

        Complaint complaint = new Complaint(
                -1,
                title,
                userID,
                complaining,
                complained,
                content,
                hidden,
                status
        );

        int rows = complaintService.addComp(complaint);
        resp.sendRedirect("/main_user.html");

    }

    // 接收管理员界面发来的处理投诉信息
    protected void statusComplaint(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String complaintId = req.getParameter("complaintId");
        // String complaintStatus = "已处理"; // 固定状态为已处理
        String complaintStatus = req.getParameter("complaintStatus");

        int rows = complaintService.statusComp(complaintId, complaintStatus);
        System.out.println(complaintId + "\t" + complaintStatus);
        resp.sendRedirect("/main_manager.html");
    }

    // 接收用户界面发来的撤回投诉信息
    protected void blackComplaint(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String complaintId = req.getParameter("complaintId");

        System.out.println("complaint ID = " + complaintId);
        int rows = complaintService.blackComp(complaintId);
        System.out.println("blackCom Rows = " + rows);
        resp.sendRedirect("/main_user.html");
    }

    // 管理员界面跳转至用户管理界面
    protected void reToUserManage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/userManager.html");
    }

    // 用户管理界面跳转至管理员界面
    protected void reToMainManager(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/main_manager.html");
    }

    // 获取用户信息
    protected void getUserInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 设置响应内容类型为JSON
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 2. 模拟数据（实际应从数据库查询）
        List<User> data = complaintService.recordUser();

        // 3. 将数据转为JSON字符串（需要引入Jackson/Gson库）
        ObjectMapper mapper = new ObjectMapper(); // Jackson库的类
        String jsonData = mapper.writeValueAsString(data);

        // 4. 返回数据给前端
        PrintWriter out = resp.getWriter();
        out.print(jsonData);
        out.flush();
    }

    // 对普通用户进行删除操作
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.sendRedirect("/userManager.html");

        // 设置响应内容类型为 JSON
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        // 创建一个 ObjectMapper 实例来解析 JSON
        ObjectMapper objectMapper = new ObjectMapper();

        // 读取请求体中的 JSON 数据
        try (BufferedReader reader = req.getReader()) {
            JsonNode jsonNode = objectMapper.readTree(reader);

            // 从 JSON 数据中提取字段值
            String id = jsonNode.get("id").asText();

            System.out.println("delete user id = " + id);
            int rows = userService.removeUser(id);
        } catch (Exception e) {
            // 处理解析 JSON 时可能发生的异常
            e.printStackTrace();
            resp.getWriter().write("{\"error\": \"Failed to parse JSON\"}");
        }

    }
}